package com.myapp.api.controller;

import com.myapp.api.entity.Admin;
import com.myapp.api.other_param.RestPassword;
import com.myapp.api.service.AdminService;
import com.myapp.api.tools.JWTUtils;
import com.myapp.api.tools.JsonResult;
import com.myapp.api.tools.MD5Utils;
import com.myapp.api.tools.ResultStatus;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;

@Api(value = "AdminController",description = "admin 表的相关 CURD 操作")
@RestController
@RequestMapping(value = "/admin", produces = "application/json;charset=UTF-8")
public class AdminController {
    @Autowired
    private AdminService service;

    @ApiOperation(value="获取管理员列表",notes="获取所有管理员信息",produces = "application/json")
    @GetMapping("/all")
    public ResponseEntity<?> getAdmins() {
        List<Admin> records = service.getAdmins();

        HttpStatus status = HttpStatus.OK;
        return new ResponseEntity<List<Admin>>(records, status);
    }

    @ApiOperation(value="获取管理员详细信息",notes="根据 url 的账号获取详细信息",produces = "application/json")
    @ApiImplicitParam(name = "account", value = "管理员账号", required = true, dataType = "Integer", paramType = "path")
    @GetMapping("/{account}")
    public ResponseEntity<?> getAdminByOneAccount(@PathVariable(value = "account") String account) {
        if (!account.equals(0) && !account.isEmpty()) {
            Admin record = service.getAdminByAccount(account);

            HttpStatus status = HttpStatus.OK;
            Object obj = new Object();
            if (record == null)
                return new ResponseEntity<Object>(obj, status);
            else
                return new ResponseEntity<Admin>(record, status);
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "管理员不能能为 0 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        }
    }

    @ApiOperation(value="新增管理员",notes="新增管理员,管理员账号不允许重复",produces = "application/json")
    @PostMapping
    public ResponseEntity<?> addAdmin(@Valid @RequestBody Admin record, BindingResult bindingResult) {
        record.setPwd(MD5Utils.encode(record.getUsername()));
        record.setCreatetime(new Date());

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            Integer findOne = service.getAdminByOneAccount(record.getAccount());

            if (!findOne.equals(0)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "重复的账号:" + record.getAccount() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else {
                int result = service.addAdmin(record);
                if (result > 0) {
                    HttpStatus status = HttpStatus.OK;
                    JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                } else {
                    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                    JsonResult jsonResult = new JsonResult(ResultStatus.ADD_DATA_ERROR);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                }
            }
        }
    }

    @ApiOperation(value="删除管理员",notes="根据 url 的 id 来删除管理员",produces = "application/json")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Integer", paramType = "path")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> delAdminById(@PathVariable(value = "id") Integer id) {
        if (!id.equals(0)) {
            int result = service.deleteAdminById(id);
            if (result > 0) {
                HttpStatus status = HttpStatus.OK;
                JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                return new ResponseEntity<JsonResult>(jsonResult, status);
            } else {
                HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
                JsonResult jsonResult = new JsonResult(ResultStatus.DELETE_DATA_ERROR, "Delete Data is Error, the id is" + id + " !!!");
                return new ResponseEntity<JsonResult>(jsonResult, status);
            }
        } else {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "id 不能为 0 !!!");
            return new ResponseEntity<JsonResult>(result, status);
        }
    }

    @ApiOperation(value="修改管理员信息",notes="修改管理员信息,管理员名字不允许重复",produces = "application/json")
    @PutMapping
    public ResponseEntity<?> putAdmin(@Valid @RequestBody Admin record, BindingResult bindingResult) {
        record.setUpdatetime(new Date());

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            Integer findOne = service.getAdminByOneAccount(record.getAccount());

            if (!findOne.equals(1)) {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "不存在的账号:" + record.getAccount() + " !!!");
                return new ResponseEntity<JsonResult>(result, status);
            } else {
                record.setUpdatetime(new Date());
                int result = service.putAdmin(record);
                if (result > 0) {
                    HttpStatus status = HttpStatus.OK;
                    JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                } else {
                    HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                    JsonResult jsonResult = new JsonResult(ResultStatus.UPDATE_DATA_ERROR);
                    return new ResponseEntity<JsonResult>(jsonResult, status);
                }
            }
        }
    }

    @ApiOperation(value="修改管理员密码",notes="修改管理员密码,需要用户身份认证（JWT）",produces = "application/json")
    @PatchMapping("/resetpwd")
    public ResponseEntity<?> repeatPassword(@Valid @RequestBody RestPassword record, BindingResult bindingResult, HttpServletRequest request) {
        String authHeader = request.getHeader(JWTUtils.TOKEN_HEADER);
        Claims claims = JWTUtils.parseJWT(authHeader);
        String account = (String) claims.get("account");
        Admin admin = service.getAdminByAccount(account);

        if (!admin.getPwd().equals(MD5Utils.encode(record.getOld_password()))) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "旧密码错误 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        } else if (!record.getNew_password().equals(record.getRepeat_password())) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult jsonResult = new JsonResult(ResultStatus.PARAMS_ERROR, "两次密码输入不一致 !!!");
            return new ResponseEntity<JsonResult>(jsonResult, status);
        } else {
            admin.setPwd(MD5Utils.encode(record.getNew_password()));
            admin.setUpdatetime(new Date());
            service.putAdmin(admin);

            HttpStatus status = HttpStatus.OK;
            JsonResult jsonResult = new JsonResult(ResultStatus.SUCCESS);
            return new ResponseEntity<JsonResult>(jsonResult, status);
        }
    }
}
